package com.nengchuan.eic.nceconomy.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 *
 * @author panwen@create
 * 2020-04-23 17:28
 */
@Component
@Slf4j
public class AsyncOperator {

    @Autowired
    private AsyncTaskExecutor asyncTaskExecutor;

    /**
     * 执行任务
     * @param task
     */
    public void execute(Runnable task){
        if(task==null){
            return;
        }
        submit(task,1);
    }

    /**
     * 提交任务
     * @param task
     * @param time 执行错误,遇到异常,需要重试两次
     */
    private void submit( Runnable task, int time) {
        try {
            Future future=asyncTaskExecutor.submit(task);
            future.get();
        }catch (InterruptedException e) {
            log.error("#submit# 线程中断异常",e);
        } catch (ExecutionException e) {
            //根据业务规定,重试任务两次
            if(time<3){
                submit(task, ++time);
            }else{
                log.error("#submit# 异步任务发生异常,重试两次依然失败后放弃;",e);
            }

        }
    }
}
